package net.sf.rose.jdbc.service;

import java.sql.Connection;
import java.sql.SQLException;

import net.sf.rose.exception.SystemErrorCode;
import net.sf.rose.exception.SystemException;
import net.sf.rose.jdbc.UserBean;
import net.sf.rose.jdbc.factory.ConnectFactory;

import org.apache.log4j.Logger;

/**
 * @author fengjian
 * @since 2012/06/23
 */
public class Service {

	private static Logger logger = Logger.getLogger(Service.class);

	/** 数据库操作的执行者 */
	private UserBean user = null;

	/** 数据库连接 */
	protected Connection con = null;

	/** 数据库连接库 */
	private ConnectFactory factory = null;

	/**
	 * 设置数据库操作的执行者
	 */
	public void setUser(UserBean user) {
		this.user = user;
	}

	/**
	 * 返回数据库操作的执行者
	 */
	public UserBean getUser() {
		return user;
	}

	/**
	 * 设置数据库连接库
	 */
	public void setConnectFactory(ConnectFactory factory){
		this.factory = factory;
	}

	/**
	 * 返回数据库连接
	 */
	public Connection getConnection() {
		if (con == null) {
			con = factory.getConnection();
		}
		return con;
	}

	/**
	 * 提交数据至数据库
	 */
	public void commit() {
		try {
			if (con != null)
				con.commit();
		} catch (SQLException e) {
			try {
				con.rollback();
			} catch (SQLException e1) {
				logger.error("数据库回滚失败!", e1);
			}
			String message = "数据更新提交至数据库失败！";
			logger.error(message, e);
			throw new SystemException(message, SystemErrorCode.D_CONNECTION_COMMIT_ERROR);
		}
	}

	/**
	 * 关闭数据库连接
	 */
	public void close() {
		if (con == null) {
			return;
		}
		try {
			con.close();
		} catch (SQLException e) {
			String message = "数据库关闭失败！";
			logger.error(message, e);
			throw new SystemException(message, SystemErrorCode.D_CONNECTION_CLOSE_ERROR);
		} finally {
			con = null;
		}
	}
}
